<?php

namespace app\pay\controller;

use app\common\exception\BusinessException;
use app\pay\logic\PayCallback;
use app\pay\service\WxCorpMcpPayService;
use think\facade\Log;
use think\Response;

class WxCorpMcpPay extends Base
{
    /**
     * notify
     */
    public function notify()
    {
        try {
            // 请求参数
            $appId = $this->request->param('appId', '');
            $header = $this->request->header();
            $inWechatPaySignature = $header['wechatpay-signature'];
            $inWechatPayTimestamp = $header['wechatpay-timestamp'];
            $inWechatPaySerial = $header['wechatpay-serial'];
            $inWechatPayNonce = $header['wechatpay-nonce'];
            $inBody = file_get_contents('php://input');

            // 记录日志
            Log::info('微信官方支付请求头：' . json_encode($header));
            Log::info('微信官方支付请求体：' . $inBody);

            // 检查参数
            if (!$appId) {
                throw new BusinessException('未获取到租户编号');
            }
            if (!$inWechatPaySignature || !$inWechatPayTimestamp || !$inWechatPaySerial || !$inWechatPayNonce || !$inBody) {
                throw new BusinessException('请求数据不合法');
            }

            // 获取回调数据
            $wxMcpData = app(WxCorpMcpPayService::class)->setAppId($appId)->getNotifyData($inWechatPayTimestamp, $inWechatPayNonce, $inBody, $inWechatPaySignature);

            // 检查解密数据
            $order_sn = $wxMcpData['out_trade_no'] ?? '';
            $transaction_id = $wxMcpData['transaction_id'] ?? '';
            if (!$order_sn || !$transaction_id) {
                throw new BusinessException('解密微信数据失败');
            }

            // 查询订单数据
            (new PayCallback())->invoke($wxMcpData['out_trade_no'], $wxMcpData['transaction_id']);
        } catch (\Exception $exception) {
            return Response::create($exception->getMessage(), 'html', 500);
        }

        return Response::create('success');
    }
}
